package com.crm.services;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.model.jdao.IDetailedDemandDAO;
import com.crm.model.jdao.IOrderInfoDao;
import com.crm.model.jdao.IOrderitemsDao;
import com.crm.model.jdao.IProductDAO;
import com.crm.model.jdao.IQuotationRecordDAO;
import com.crm.model.jdao.ISalesOpportunityDAO;
import com.crm.model.jdao.ISalesTrackingLogDAO;
import com.crm.model.jdao.IShowsettingSalesOpportunityDAO;
import com.crm.model.pojo.Competitor;
import com.crm.model.pojo.Customer;
import com.crm.model.pojo.DetailedDemand;
import com.crm.model.pojo.Orderinfo;
import com.crm.model.pojo.Orderitem;
import com.crm.model.pojo.QuotationDetail;
import com.crm.model.pojo.QuotationRecord;
import com.crm.model.pojo.SalesOpportunity;
import com.crm.model.pojo.Solution;

/**
 * 报价记录
 * @author 飞鱼
 *
 */
@Service
public class QuotationRecordService {

	@Autowired
	IOrderInfoDao iOrder;
	@Autowired
	private IQuotationRecordDAO QuotationRecordDAO;
	@Autowired
	private QuotationRecordService qrsDAO;
	@Autowired
	private SalesOpportunityServices ss;
	@Autowired
	private DictionaryServices ds;
	@Autowired
	private UserServices us;	
	@Autowired
	private ISalesTrackingLogDAO salLogDAO;
	@Autowired
	private ContactServices cs;
	@Autowired	
	private QuotationDetailServices qds;
	@Autowired
	IOrderitemsDao iOrderitemsDao;
	@Autowired
	private IProductDAO prdDAO;
	@Autowired
	private CompetitorServices coms;
	private static int count=0;
	
	/**
	 * 报价记录新增
	 * @param sale
	 * @return
	 */
	public int save(QuotationRecord newsale) {
		if(newsale.getSalesOpportunity().getSalStage()<1329) {
			newsale.getSalesOpportunity().setSalStage(1329);
			ss.save(newsale.getSalesOpportunity());
		}
		QuotationRecordDAO.save(newsale);		
		return 1;		
	}
	/**
	 * 
	 * @param pageNumber  从那天开始显示
	 * @param pageContent 显示的记录条数
	 * @return
	 */
	public List<QuotationRecord> queryByAll(int pageNumber,int pageContent,String[] DId){
		Sort sort=Sort.by(Direction.DESC, "qdRecordId");
		Pageable pageable =PageRequest.of(pageNumber,pageContent,sort);	
		//查询条件构造
		 Specification<QuotationRecord> spec=new Specification<QuotationRecord>(){

			@Override
			public Predicate toPredicate(Root<QuotationRecord> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				//Path<Object> state=root.get("state");
				List<Predicate> list=new ArrayList<>();
				System.out.println("ss的DId:"+DId);
					if(DId.length==0) {
						list.add(cb.equal(root.get("state").as(Integer.class), 1));
					}
					int i=0;
					for (String str : DId) {
						System.out.println("str:"+str);
						if("全部数据".equals(str)) {
							 list.add(cb.equal(root.get("state").as(Integer.class), 1));	
						}
						if("客户名称".equals(str)) {
							System.out.println("触发了模糊客户名称数据筛选");	
							//cb.countDistinct(root.join("customer").get("custName")));
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.join("customer").get("custName").as(String.class),"%"+DId[i+2]+"%"));									
							}else {
								list.add(cb.like(root.join("customer").get("custName").as(String.class),"%"+DId[i+1]+"%"));
							    query.groupBy(root.get("customer").as(Customer.class));
							}

						}
						if("报价主题".equals(str)) {
							System.out.println("触发了模糊方案主题数据筛选");	
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.get("qrTheme").as(String.class),"%"+DId[i+2]+"%"));								
							}else {
								list.add(cb.like(root.get("qrTheme").as(String.class),"%"+DId[i+1]+"%"));
							}

							//cb.countDistinct(root.join("customer").get("custName")));
							
						}
						if("机会主题".equals(str)) {
							System.out.println("触发了模糊机会主题数据筛选");	
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.join("salesOpportunity").get("salTheme").as(String.class),"%"+DId[i+2]+"%"));									
							}else {
								list.add(cb.like(root.join("salesOpportunity").get("salTheme").as(String.class),"%"+DId[i+1]+"%"));	
								query.groupBy(root.get("salesOpportunity").as(SalesOpportunity.class));
							}							
													
						}
						i++;
					}

		        Predicate[] p = new Predicate[list.size()];
		        System.out.println("-----------------------------------------");
			    query.where(list.toArray(p));
				return query.getRestriction();
			}
			 
		 };
		Page<QuotationRecord> page =QuotationRecordDAO.findAll(spec,pageable);		
		System.out.println("总记录数："+page.getTotalElements());
		count=(int) page.getTotalElements();
		List<QuotationRecord> list=page.getContent();
		return list;		
	}
	
	/**
	 *将list的数据转换成JsonArray的数据
	 * @return
	 */
	public JSONArray ListTransJSONArray(int pageNumber,int pageContent,String[] DId) {
		JSONArray array =new JSONArray();
		List<QuotationRecord> list=qrsDAO.queryByAll(pageNumber,pageContent,DId);
		for (QuotationRecord Competitor : list) {
		//System.out.println("Competitor:"+Competitor);
			JSONObject obj = new JSONObject();		
			array.add(toJSONObject1( obj,Competitor));
	}
		return array;
	}
	
	/**
	 * 报价记录转JSONObject
	 * @param obj
	 * @param Competitor
	 * @return
	 */
	public JSONObject toJSONObject1(JSONObject obj,QuotationRecord Competitor) {
		/*obj.put("salId", Competitor.getSalId());
		obj.put("salTheme", Competitor.getSalTheme());
		obj.put("custName", Competitor.getCustomer().getCustName());
		String starURL=ss.starURL(Competitor.getStarStandard());
		obj.put("starStandard",starURL);
		obj.put("salType", ds.findByDictId(Competitor.getSalType()));
		if(Competitor.getSotlDate()!=null) {
			obj.put("sotlDate",Competitor.getSotlDate().toString());			
		}				
		obj.put("sotlMoney", Competitor.getSotlMoney());
		obj.put("custDemand", Competitor.getCustDemand());
		obj.put("salStageStop", Competitor.getSalStageStop()+"天");
		obj.put("salState",Competitor.getSalState());
		obj.put("salSource", ds.findByDictId(Competitor.getSalSource()));
		obj.put("sotlId", ss.findByUserName(Competitor.getSotlId()));
		obj.put("salState", ds.findByDictId(Competitor.getSalState())+"");		
		obj.put("salPossibility", ds.findByDictId(Competitor.getSalPossibility()));
		obj.put("salUpdatetime", Competitor.getSalUpdatetime().toString());
		//obj.put("", value);*/
		obj.put("qdRecordId", Competitor.getQdRecordId());//报价记录id
		//obj.put("deliveryInstructions", Competitor.getDeliveryInstructions());//交付说明
		obj.put("generalQuotation",coms.price(Competitor.getGeneralQuotation()));//	总报价
		//obj.put("paymentInstructions",Competitor.getPaymentInstructions());//付款说明
		if( Competitor.getQrDate()!=null) {
			obj.put("qrDate", Competitor.getQrDate().toString());//报价日期			
		}else {
			obj.put("qrDate", "");//报价日期
		}

		//obj.put("qrExplain",Competitor.getQrExplain());//包装运输说明
		obj.put("qrOfferor",us.findByUId(Competitor.getQrOfferor()).getUName());//报价人，用户
		//obj.put("qrOfferphone",Competitor.getQrOfferphone());//报价人联系方式
		obj.put("qrReceiver",cs.findByConId(Competitor.getQrReceiver()).getConName());//接收人,就是联系人
		obj.put("qrTheme",Competitor.getQrTheme());//报价主题
		//obj.put("quotationFile",Competitor.getQuotationFile());//上传附件
		//obj.put("quotationNo",Competitor.getQuotationNo());//报价单号
		//obj.put("state",Competitor.getState());//状态
		if(null!=Competitor.getSalesOpportunity()) {
			obj.put("salTheme",Competitor.getSalesOpportunity().getSalTheme());			
		}else {
			obj.put("salTheme","");			
		}

		obj.put("customer", Competitor.getCustomer().getCustName());
		return obj;
	}
	
	
	/** 销售机会转JSONObject,单一saleOpp
	 * @param obj
	 * @param Competitor
	 * @return
	 */
	public JSONObject toJSONObject2(JSONObject obj,QuotationRecord Competitor) {
		/*
		obj.put("salId", Competitor.getSalId());
		obj.put("salTheme", Competitor.getSalTheme());
		obj.put("customerName", Competitor.getCustomer().getCustName());
		obj.put("customerId", Competitor.getCustomer().getCustId()+"");			
		obj.put("starStandard",Competitor.getStarStandard()+"");
		
		obj.put("salTypelabel", ds.findByDictId(Competitor.getSalType()));
		obj.put("salTypeValue", Competitor.getSalType());
		
		//obj.put("sotlId", Competitor.getSotlId());	
		if(Competitor.getSotlDate()!=null) {
			obj.put("sotlDate",Competitor.getSotlDate().toString());			
		}		
		obj.put("sotlMoney", Competitor.getSotlMoney());
		//
		obj.put("custDemand", Competitor.getCustDemand());
		
		obj.put("salStageStop", Competitor.getSalStageStop()+"天");		
		obj.put("salState", Competitor.getSalState()+"");		
		obj.put("salPossibilitylabel", ds.findByDictId(Competitor.getSalPossibility()));

		obj.put("sotlId", ss.findByUserName(Competitor.getSotlId()));
		obj.put("salStagelabel", ds.findByDictId(Competitor.getSalStage()));
		obj.put("salStageNotes", Competitor.getSalStageNotes());
		
		obj.put("salSourcelabel", ds.findByDictId(Competitor.getSalSource()));
		if(Competitor.getContact()!=null) {
			obj.put("contactName", Competitor.getContact().getConName()+"");			
		}else {
			obj.put("contactName","");				
		}
		obj.put("contactId", Competitor.getContact().getConId());
		*/
		obj.put("qd_recordId", Competitor.getQdRecordId());//报价记录id
		obj.put("deliveryInstructions", Competitor.getDeliveryInstructions());//交付说明
		obj.put("generalQuotation",Competitor.getGeneralQuotation());//	总报价
		obj.put("paymentInstructions",Competitor.getPaymentInstructions());//付款说明
		obj.put("qrDate", Competitor.getQrDate());//报价日期
		obj.put("qrExplain",Competitor.getQrExplain());//包装运输说明
		
		obj.put("qrOfferor",us.findByUId(Competitor.getQrOfferor()).getUName());//报价人，用户
		obj.put("userId", us.findByUId(Competitor.getQrOfferor()).getUId());
		
		obj.put("qrOfferphone",Competitor.getQrOfferphone());//报价人联系方式
		
		obj.put("qrReceiver",cs.findByConId(Competitor.getQrReceiver()).getConName());//接收人,就是联系人
		obj.put("conID",cs.findByConId(Competitor.getQrReceiver()).getConId());//接收人,就是联系人		
		
		obj.put("qrTheme",Competitor.getQrTheme());//报价主题
		obj.put("quotationFile",Competitor.getQuotationFile());//上传附件
		//obj.put("quotationNo",Competitor.getQuotationNo());//报价单号
		//obj.put("state",Competitor.getState());//状态
		if(null!=Competitor.getSalesOpportunity()) {
			obj.put("salesOpportunityName",Competitor.getSalesOpportunity().getSalTheme());			
		}else {
			obj.put("salesOpportunityName",Competitor.getSalesOpportunity().getSalTheme());					
		}

		obj.put("salesOpportunityId", Competitor.getSalesOpportunity().getSalId());
		//obj.put("customer", Competitor.getCustomer().getCustName());
		obj.put("customerName", Competitor.getCustomer().getCustName());
		obj.put("customerId", Competitor.getCustomer().getCustId()+"");	
		return obj;
	}
	
	/**
	 * 将list的数据转换成JsonArray的数据,用于页面搜索查询客户信息
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray1(List<QuotationRecord> list) {
		JSONArray array = new JSONArray();
		for (QuotationRecord Competitor : list) {
			// System.out.println("Competitor:"+Competitor);
			JSONObject obj = new JSONObject();
			
			obj.put("value", Competitor.getCustomer().getCustName());
			obj.put("label1", Competitor.getCustomer().getCustId());
			array.add(obj);
		}
		return array;
	}	
	
	/**
	 * 将list的数据转换成JsonArray的数据,用于页面搜索查询销售机会主题名称信息
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray3(List<QuotationRecord> list) {
		JSONArray array = new JSONArray();
		for (QuotationRecord salesOpportunity : list) {
			// System.out.println("salesOpportunity:"+salesOpportunity);
			JSONObject obj = new JSONObject();
			obj.put("value", salesOpportunity.getSalesOpportunity().getSalTheme());
			array.add(obj);
		}
		return array;
	}
	/**
	 * 将list的数据转换成JsonArray的数据,用于页面搜索查询报价主题信息
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray4(List<QuotationRecord> list) {
		JSONArray array = new JSONArray();
		for (QuotationRecord Competitor : list) {
			// System.out.println("Competitor:"+Competitor);
			JSONObject obj = new JSONObject();
			
			obj.put("value", Competitor.getQrTheme());
			array.add(obj);
		}
		return array;
	}	
	/**
	 * 统计对象个数
	 * @return
	 */
	public int queryByCount() {
		return count;
		
	}
	  /**
	   * 根据id查询竞争对手
	   * @param salId
	   * @return
	   */
	public  JSONObject findBySalId(Integer salId) {
		QuotationRecord sale=QuotationRecordDAO.queryByrecordId(salId);
		JSONObject obj = new JSONObject();	
		return toJSONObject2(obj,sale);
		  
	  }
	/**
	 * 删除单个销售机会
	 * @param salId
	 * @return
	 */
	public void Delete(Integer salId) {
		QuotationRecord sal=QuotationRecordDAO.findById(salId).get();
		sal.setState(0);
		QuotationRecordDAO.save(sal);		
	}
	
	/**
	 * 确认报价主题是否重复
	 * @param qrTheme
	 * @return
	 */
	public Integer findByQrTheme(String qrTheme) {
		QuotationRecord sale=QuotationRecordDAO.findByQrTheme(qrTheme);
		if(sale!=null) {
			return sale.getQdRecordId();
		}
		return 0;
		
	}
	/**
	 * 批量逻辑删除
	 * @param salIds
	 */
/*	public void DeleteAll(Iterable<Integer> salIds) {
		//Integer[] ff=new Integer[] {1,2,3};
		List list=new ArrayList();
		list.add(1);
		Iterable<Integer> dd=(Iterable<Integer>) list.iterator();
		ss.DeleteAll(dd);		
		Iterable<Competitor> a=CompetitorDAO.findAllById(salIds);
		for (Competitor Competitor : a) {
			Competitor.setState(0);
		}
		CompetitorDAO.saveAll(a);
	}*/
	
	/**
	 * 转成订单
	 * @return 
	 */
	public Integer changeToOrder(Integer qId) {
		
		/*
		orderinfo.setCustomer(findByCustName);//客户
		orderinfo.setOTitle(otitle);//主题
		orderinfo.setOType(otype);//订单分类
		orderinfo.setOPay(orderpay);//付款方式
		orderinfo.setOData(java.sql.Date.valueOf(date1.substring(0,10)));//订单创建时间
		orderinfo.setOFadate(java.sql.Date.valueOf(date2));//订单最晚发货时间
		orderinfo.setOSign(osign);//客户签约人
		orderinfo.setUId(uid);//订单所有人
		orderinfo.setOConsignee(oconsignee);//收货人
		orderinfo.setoConphone(conphone);//收货人电话
		orderinfo.setOAddress(contaddress);//收货地址
		orderinfo.setOPostcode(postcode);//邮编
		orderinfo.setORemark(remark);//备注
		orderinfo.setODstatus(radiosatus);//订单状态
		orderinfo.setOShipments(1093);//发货状态
		orderinfo.setOSalesreturn(1096);
		orderinfo.setOStatus(1102);
		orderinfo.setOSummoney(new BigDecimal("10000"));*/
		List<QuotationDetail> jsons=qds.findByQuotationRecord(qId);
		if(jsons.size()==0) {
			return null;
		}
		QuotationRecord qr=QuotationRecordDAO.queryByrecordId(qId);		
		Orderinfo orderinfo=new Orderinfo();
		orderinfo.setCustomer(qr.getCustomer());
		orderinfo.setOTitle("自动转换的订单"+qr.getQdRecordId());
		orderinfo.setOType(1254);  
		orderinfo.setOPay(1090);
		orderinfo.setOData(new Date()); 
		orderinfo.setOSign(1);//是客户还是联系人呢？
		orderinfo.setUId(qr.getQrOfferor());//这是处理cookie传值
		orderinfo.setOConsignee(cs.findByConId(qr.getQrReceiver()).getConName());
		orderinfo.setoConphone(qr.getQrOfferphone());
		orderinfo.setODstatus(1098);
		orderinfo.setOShipments(1093);//发货状态
		orderinfo.setOSalesreturn(1096);
		orderinfo.setOStatus(1102);

		Orderinfo s=iOrder.save(orderinfo);
		System.out.println(s.getOId());
		BigDecimal sumMoney=new BigDecimal(0);
		for (QuotationDetail quotationDetail : jsons) {
			Orderitem orderitem =new Orderitem();
/*			orderitem.setProduct(product);
			orderitem.setOrderinfo(orderinfo);
			orderitem.setCustId(comcustid);
			orderitem.setOiPrice(new BigDecimal(price));
			orderitem.setOiMoney(new BigDecimal(money));
			orderitem.setOiDiscount(new BigDecimal(discount));
			orderitem.setOiCount(new BigDecimal(count));
			orderitem.setOiDate(java.sql.Date.valueOf(date));
			orderitem.setConditions(conditions);
			orderitem.setRemark(remark);
			orderitem.setuId(uid);
			orderitem.setStatus(1102);*/
			orderitem.setCustId(qr.getCustomer().getCustId());
			orderitem.setOrderinfo(s);
			orderitem.setProduct(prdDAO.findByPId(quotationDetail.getQdProduct()));
			orderitem.setOiPrice(quotationDetail.getQdPrice());
			orderitem.setOiMoney(quotationDetail.getMoney());
			orderitem.setOiDiscount(quotationDetail.getDiscount());
			orderitem.setOiCount(new BigDecimal(quotationDetail.getQdNumber()));
			orderitem.setOiDate(new Date());
			orderitem.setRemark(quotationDetail.getQdNotes());
			orderitem.setuId(qr.getQrOfferor());
			orderitem.setStatus(1102);
			sumMoney=sumMoney.add(quotationDetail.getMoney());
			iOrderitemsDao.save(orderitem);
		}
		orderinfo.setOSummoney(sumMoney);
		iOrder.save(orderinfo);
		if(qr.getSalesOpportunity().getSalStage()<1330) {		
			qr.getSalesOpportunity().setSalStage(1330);
			ss.save(qr.getSalesOpportunity());
		}
		return 1;
	}
	
}
